<template>
  <div>
    <section class="jarallax py-5">
      <img src="@/assets/images/banner-1.jpg" class="jarallax-img">
      <div class="hero-content py-0 py-md-5">
        <div class="container-lg d-flex flex-column d-md-block align-items-center">
          <nav class="breadcrumb">
            <a class="breadcrumb-item nav-link" href="/Organic/home">主页</a>
            <a class="breadcrumb-item nav-link" href="/Organic/shop">页面</a>
            <span class="breadcrumb-item active" aria-current="page">分类</span>
          </nav>
          <h1>分类</h1>
        </div>
      </div>
    </section>

    <div class="py-4">
      <div class="container-lg">
        <div class="row g-5">
          <aside class="col-md-2">
            <div class="sidebar">
              <div class="widget-menu">
                <div class="widget-search-bar">
                  <form role="search" method="get" class="d-flex position-relative">
                    <form class="d-flex mt-3 gap-0" >
                      <input class="form-control form-control-lg rounded-2 bg-light" type="email" placeholder="Search here" aria-label="Search here" v-model="searchData.keyword">
                      <button type="button" @click="InitializeThePage" class="btn bg-transparent position-absolute end-0" ><svg width="24" height="24" viewBox="0 0 24 24"><use xlink:href="#search"></use></svg></button>
                    </form>
                  </form>
                </div>
              </div>
              <div class="widget-product-categories pt-5">
                <h5 class="widget-title">分类</h5>
                <el-cascader :options="options" @change="handleChange" clearable></el-cascader>
              </div>
            </div>
          </aside>

          <main class="col-md-10">
            <div class="filter-shop d-flex justify-content-between">
              <div class="showing-product">
                <p>显示 1-10 个结果（共 25 个结果）</p>
              </div>
<!--              <div class="sort-by">-->
<!--                <select id="input-sort" class="form-control" data-filter-sort="" data-filter-order="">-->
<!--                  <option value="">默认排序</option>-->
<!--                  <option value="">Name (A - Z)</option>-->
<!--                  <option value="">Name (Z - A)</option>-->
<!--                  <option value="">Price (Low-High)</option>-->
<!--                  <option value="">Price (High-Low)</option>-->
<!--                  <option value="">Rating (Highest)</option>-->
<!--                  <option value="">Rating (Lowest)</option>-->
<!--                  <option value="">Model (A - Z)</option>-->
<!--                  <option value="">Model (Z - A)</option>-->
<!--                </select>-->
<!--              </div>-->
            </div>

            <div class="product-grid row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-3 row-cols-xl-4 row-cols-xxl-5">
              <div class="col" v-for="product in tableData" :key="product.id">
                <div class="product-item">
                  <figure>
                    <a href="javascript: void(0)" @click="details(product)" title="Product Title">
                      <img :src="'http://localhost:90'+product.imgLink" alt="Product Thumbnail" class="tab-image">
                    </a>
                  </figure>
                  <div class="d-flex flex-column text-center">
                    <h3 class="fs-6 fw-normal">{{product.name}}</h3>
                    <div class="d-flex justify-content-center align-items-center gap-2">
                      <span class="text-dark fw-semibold">￥{{product.price}}</span>
                    </div>
                    <div class="button-area p-3 pt-0">
                      <div class="row g-1 mt-2">
                        <div class="col-3">
                          <input type="number" name="quantity" class="form-control border-dark-subtle input-number quantity" v-model="product.num" min="1" :max="product.stock">
                        </div>
                        <div class="col-7">
                          <a href="javascript:void(0)" class="btn btn-primary rounded-1 p-2 fs-7 btn-cart" @click="addToCart(product)">
                            <svg width="18" height="18">
                              <use xlink:href="javascript:void(0)" ></use>
                            </svg>
                            加入购物车
                          </a>
                        </div>
                        <div class="col-2">
                          <a href="#" class="btn btn-outline-dark rounded-1 p-2 fs-6">
                            <svg width="18" height="18"><use xlink:href="#heart"></use>
                            </svg>
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- / product-grid -->

<!--            <nav class="text-center py-4" aria-label="Page navigation">-->
<!--              <ul class="pagination d-flex justify-content-center">-->
<!--                <li class="page-item disabled">-->
<!--                  <a class="page-link bg-none border-0" href="#" aria-label="Previous">-->
<!--                    <span aria-hidden="true">&laquo;</span>-->
<!--                  </a>-->
<!--                </li>-->
<!--                <li class="page-item active" aria-current="page"><a class="page-link border-0" href="#">1</a></li>-->
<!--                <li class="page-item"><a class="page-link border-0" href="#">2</a></li>-->
<!--                <li class="page-item"><a class="page-link border-0" href="#">3</a></li>-->
<!--                <li class="page-item">-->
<!--                  <a class="page-link border-0" href="#" aria-label="Next">-->
<!--                    <span aria-hidden="true">&raquo;</span>-->
<!--                  </a>-->
<!--                </li>-->
<!--              </ul>-->
<!--            </nav>-->
            <br>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
          </main>

        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ShopBody',
  components: {},
  props: {},
  data () {
    return {
      user: this.$store.state.user,
      currentPage : 1,
      total : 0,
      pageSize : 10,
      level1Category:[],
      secondaryCategory:[],
      options:[],
      typeId:[],
      searchData:{
        keyword:'' // 初始化keyword为空字符串
      },
      type:'',
      tableData: []
    }
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    handleSizeChange(val) {//页大小改变时
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.InitializeThePage();
    },
    handleCurrentChange(val) {//页码发生改变时
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.InitializeThePage();
    },
    InitializeThePage() {
      Object.assign(this.searchData, {"currentPage": this.currentPage, "pageSize": this.pageSize,"typeId": this.type})
      this.$axios.post('http://localhost:8090/product/getProductBySearchData', this.searchData).then(({ data }) => {
        this.tableData = data.records;
        this.total = data.total;
        if (data.records.length === 0) {
          this.$notify({
            title: '没有找到相关商品',
            message: '没有找到相关商品，请重新输入',
            type: 'warning'
          });
        }
      });
    },
    details(product){
      this.$store.commit('initProduct', product)
      this.$router.push({ path: '/Organic/product' })
    },
    addToCart(product){
      let formData = new FormData();
      formData.append('productId', product.productId);
      formData.append('num', product.num);
      formData.append('consumerId', this.user.consumerId);
      this.$axios.post('http://localhost:8090/cart/addToCart', formData).then(({ data }) => {
        if (data) {
          this.$notify({
            title: '添加成功',
            message: '添加成功！',
            type: 'success'
          });
          this.intCart()
          this.$forceUpdate(); // 强制重新渲染，触发计算属性更新
        }else{
          this.$notify({
            title: '添加失败',
            message: '添加失败，请稍后重试',
            type: 'warning'
          });
        }
      });
    },
    intCart(){
      this.$axios.get('http://localhost:8090/cart/getCartByConsumerId?consumerId=' + this.user.consumerId).then(({ data }) => {
        // eslint-disable-next-line no-empty
        if(data !== null && data !== undefined ){
          this.carts = data;
          console.log(this.carts);
          this.$store.commit('initCarts', this.carts)
          console.log(this.$store.state.carts);
        }
      })
    },
    initialTypeSelect: function () {
      this.$axios.get("http://localhost:8090/product-type/getAllProductType?level="+1).then(({ data }) => {
        this.level1Category = data;
        this.$axios.get("http://localhost:8090/product-type/getAllProductType?level="+2).then(({ data }) => {
          this.secondaryCategory = data;
          this.getOptions(this.level1Category, this.secondaryCategory);
        })
      })

    },
    getOptions(level1Category, secondaryCategory){
      let options = [];
      for (let i = 0; i < level1Category.length; i++) {
        let item = {
          label: level1Category[i].typeName,
          value: level1Category[i].typeId,
          children: []
        }
        for (let j = 0; j < secondaryCategory.length; j++) {
          if (level1Category[i].typeId === secondaryCategory[j].parentId) {
            item.children.push({
              label: secondaryCategory[j].typeName,
              value: secondaryCategory[j].typeId
            })
          }
        }
        options.push(item);
      }
      this.options = options;
    },
    handleChange(value) {
      if (value.length !== 0){
        this.type = value[0] + "-" + value[1];
      }else if (value.length === 0){
        this.type = "";
      }
      this.InitializeThePage();
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 解析URL并获取keyword参数
    const urlParams = new URLSearchParams(window.location.search);
    this.searchData.keyword = urlParams.get('keyword') || '';
    this.InitializeThePage(); // 初始化页面数据
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.initialTypeSelect();
    // this.InitializeThePage();
  },
  // 生命周期 - 创建之前
  beforeCreate () {},
  // 生命周期 - 挂载之前
  beforeMount () {},
  // 生命周期 - 更新之前
  beforeUpdate () {},
  // 生命周期 - 更新之后
  updated () {},
  // 生命周期 - 销毁之前
  beforeDestroy () {},
  // 生命周期 - 销毁完成
  destroyed () {},
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated () {}
}
</script>

<style scoped>

</style>
